package com.stars.easyms.swagger.plugin;

import com.google.common.base.Optional;
import com.stars.easyms.rest.annotation.EasyMsRestMapping;
import com.stars.easyms.rest.bean.RestInfo;
import com.stars.easyms.rest.constant.RestConstants;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.env.Environment;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;
import springfox.documentation.spring.web.DescriptionResolver;
import springfox.documentation.swagger.common.SwaggerPluginSupport;

/**
 * <p>className: EasyMsOperationSummaryReader</p>
 * <p>description: 设置swagger上显示rest的接口名称</p>
 *
 * @author guoguifang
 * @version 1.2.1
 * @date 2019-07-04 17:36
 */
public final class EasyMsOperationSummaryReader implements OperationBuilderPlugin {

    private final DescriptionResolver descriptions;

    public EasyMsOperationSummaryReader(DescriptionResolver descriptions, Environment environment) {
        this.descriptions = descriptions != null ? descriptions : new DescriptionResolver(environment);
    }

    @Override
    public void apply(OperationContext context) {
        Optional<EasyMsRestMapping> restRequestMappingAnnotation = context.findAnnotation(EasyMsRestMapping.class);
        if (restRequestMappingAnnotation.isPresent()) {
            EasyMsRestMapping easyMsRestMapping = restRequestMappingAnnotation.get();
            String summary = easyMsRestMapping.name();
            if (StringUtils.isBlank(summary)) {
                Optional<ApiOperation> apiOperationAnnotation = context.findAnnotation(ApiOperation.class);
                if (apiOperationAnnotation.isPresent()) {
                    summary = apiOperationAnnotation.get().value();
                } else {
                    RestInfo restInfo = RestConstants.REGISTER_REQUEST_MAPPING_PATH_MAP.get(context.requestMappingPattern());
                    summary = restInfo != null ? restInfo.getName() : context.getName();
                }
            }
            context.operationBuilder().summary(descriptions.resolve(summary));
        }
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return SwaggerPluginSupport.pluginDoesApply(delimiter);
    }
}